﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using HinduShop.DbClassLib;
using HinduShop.Domain.Models;
using HinduShop.UI.ViewModels.StoreManager;

namespace HinduShop.UI.Controllers
{   
    //[Authorize(Roles = "Administrator")]
    public class StoreManagerController : Controller
    {
        private readonly IRepository<Product> productRepository;
        private readonly IRepository<Category> categoryRepository;

        private readonly IUnitOfWorkFactory unitOfWorkFactory;

        public StoreManagerController(
            IRepository<Product> productRepositoryParam, 
            IRepository<Category> categoryRepositoryParam, 
            IUnitOfWorkFactory OUWFParam)
        {
            productRepository = productRepositoryParam;
            categoryRepository = categoryRepositoryParam;
            unitOfWorkFactory = OUWFParam;
        }

        //
        // GET: /StoreManager/

        public ActionResult Index()
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                IEnumerable<Product> products = productRepository.ReadAll();

                var productList = new ProductListViewModel(products);

                uow.TransactionalFlush();

                return View(productList);

                //if (HttpContext.User.Roles & RolesEnum.Administrator != 0)
                //    return View("Index_admin", productList);
                //if (HttpContext.User.Roles & RolesEnum.User != 0)
                //    return View("Index_user", productList);
            }
        }

        //
        // GET: /StoreManager/Edit/5

        public ActionResult Edit(int id)
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                Product product = productRepository.ReadById(id);

                IEnumerable<Category> categoryList = categoryRepository.ReadAll();

                var model = new EditProductViewModel(product, categoryList);

                uow.TransactionalFlush();

                return View(model);
            }
        }

        //
        // GET: /StoreManager/Details/5

        public ActionResult Details(int id)
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                var product = productRepository.ReadById(id);
                var productViewModel = new ProductViewModel(product);

                uow.TransactionalFlush();
                
                return View(productViewModel);
            }
        }

        //
        // GET: /StoreManager/Create

        public ActionResult Create()
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                IEnumerable<Category> categoryList = categoryRepository.ReadAll();
                var model = new EditProductViewModel(categoryList); // заливаем в модель список категорий

                uow.TransactionalFlush();

                return View(model);
            }

            
        } 

        //
        // POST: /StoreManager/Create

        [HttpPost]
        public ActionResult Create(ProductViewModel model)
        {
            if (ModelState.IsValid == false)
            {
                return View(model);
            }

            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                // Automapper
                var product = new Product { Name = model.ProductName, Price = model.ProductPrice };

                Category category = categoryRepository.ReadByName("Name", model.CategoryName);
                product.Category = category;

                productRepository.SaveItem(product);

                TempData["message"] = string.Format("{0} успешно добавлен", model.ProductName);

                uow.TransactionalFlush();
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /StoreManager/Edit/5

        [HttpPost]
        public ActionResult Edit(ProductViewModel model)
        {
            if (ModelState.IsValid == false)
                return View(model);

            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                Product product = productRepository.ReadById(model.ProductId);
                if (product == null)
                    throw new Exception("Продукт не считался из репозитория");
                product.Price = model.ProductPrice;

                if (model.Image != null)
                {
                    product.ImageMimeType = model.Image.ContentType;
                    product.ImageData = new byte[model.Image.ContentLength];
                    model.Image.InputStream.Read(product.ImageData, 0, model.Image.ContentLength);
                }

                productRepository.UpdateItem(product);

                TempData["message"] = string.Format("{0} успешно сохранен", model.ProductName);

                uow.TransactionalFlush();

                return RedirectToAction("Index");
            }
        }

        //
        // POST: /StoreManager/Delete/5
        public ActionResult Delete(int id)
        {
            using (IUnitOfWork uow = unitOfWorkFactory.Create())
            {
                var product = productRepository.ReadById(id);
                if (product != null)
                {
                    productRepository.DeleteItem(product);
                    TempData["message"] = string.Format("{0} удален успешно", product.Name);
                }
                uow.TransactionalFlush();
            }
            
            return RedirectToAction("Index");
        }

        public FileContentResult GetImage(int productId)
        {
            Product product = productRepository.ReadById(productId);
            if (product != null)
            {
                return File(product.ImageData, product.ImageMimeType);
            }
            return null;
        }

    }
}
